package com.platform.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.platform.annotation.RequestBean;
import com.platform.base.PageUtil;
import com.platform.base.R;
import com.platform.base.mvc.BaseController;
import com.platform.dto.Dict;
import com.platform.logger.annotation.ApiLog;
import com.platform.service.IDict;
import com.platform.utils.StringUtils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * 
 * <p> Title:Zd Mapper</p>
 * <p> Description:  字典表</p>
 * <p> Copyright: Copyright (c) 2019 </p>
 * <p> Company: </p>
 *
 * @author wys
 * @version 1.0
 */
@SuppressWarnings("all")
@Controller
@RequestMapping("/dict") 
@Api(tags="OMS-数据字典模块")
@Validated
public class DictController extends BaseController{
	
	@Autowired
    private IDict services;
	
    @RequestMapping(value="data",method=RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value="分页获取系统模块菜单资源")
	@ApiImplicitParams({
        @ApiImplicitParam(name = "dto", value = "字典数据实体", required = true, dataType = "Dict"),
        @ApiImplicitParam(name = "start", value = "起始页", required = true, dataType = "int"),
        @ApiImplicitParam(name="limit",value="每页显示大小",required = true,dataType="int")
	})
    public Object selectAll(@RequestBean Dict dto,Integer start,Integer limit,HttpServletRequest request, HttpServletResponse response,
            HttpSession session) {
        PageUtil pageUt = new PageUtil();
        pageUt.setPageIndex(start);
        pageUt.setPageSize(limit);
        if(dto.getParent() == null) {
        	dto.setParent(2L);
        }
        pageUt.setParams(BeanUtil.beanToMap(dto));
        List<Dict> servicesList = services.selectByPaging(pageUt);
        return R.success(servicesList, pageUt.getTotal());
    }
    
    @RequestMapping(value="combobox",method= {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    @ApiOperation(value="根据字典类型获取字典数据提供给前端下拉框使用")
	@ApiImplicitParams({
        @ApiImplicitParam(name = "type", value = "字典类型分类", required = true, dataType = "String")
	})
    public Object comboBoxByDict(HttpServletRequest request,String type){
    	Map<String,Object> searchMap = MapUtil.newHashMap();
    	searchMap.put("type", type);
    	searchMap.put("state",1);
    	List<Dict> dictList = services.selectAll(searchMap);
    	Map<String,Object> searchMap2 = MapUtil.newHashMap();
    	if(dictList.size() != 0) {
    		searchMap2.put("parent",dictList.get(0).getId());
    	}else {
    		searchMap2.put("parent",-2);
    	}
    	Map<String,Object> resultMap = MapUtil.newHashMap();
    	resultMap.put("root", services.selectAll(searchMap2));
    	return resultMap;
    } 
    
    @RequestMapping(value="comboboxChildren",method=RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value="根据字典类型和字典值获取下级数据，可用于下拉树结构")
	@ApiImplicitParams({
        @ApiImplicitParam(name = "type", value = "字典类型分类", required = true, dataType = "String"),
        @ApiImplicitParam(name = "code", value = "字典值", required = true, dataType = "String")
	})
    public Object comboBoxByDictChildren(HttpServletRequest request,String type,String code){
    	Map<String,Object> searchMap = MapUtil.newHashMap();
    	searchMap.put("type", type);
    	searchMap.put("state",1);
		searchMap.put("parent",code);
    	List<Dict> dictList = services.selectAll(searchMap);
    	Map<String,Object> resultMap = MapUtil.newHashMap();
    	resultMap.put("root", dictList);
    	return resultMap;
    } 
    
    @RequestMapping(value="zTree2",method= {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    @ApiOperation(value="根据字典类型和字典值获取下级数据，主要是给zTree提供使用")
	@ApiImplicitParams({
        @ApiImplicitParam(name = "type", value = "字典分类类型", required = true, dataType = "String"),
        @ApiImplicitParam(name = "code", value = "字典值", required = true, dataType = "String")
	})
    public Object Ztree2(HttpServletRequest request,String type,String code){
    	Map<String,Object> searchMap = MapUtil.newHashMap();
    	searchMap.put("type", type);
    	searchMap.put("state",1);
    	if(!StringUtils.isEmpty(code)){
    		searchMap.put("parent",code);
    	}
    	Map<String,Object> resultMap = MapUtil.newHashMap();
    	List<Map<String,Object>> resultZtreeDate = new ArrayList<Map<String,Object>>();
    	List<Dict> dictList = services.selectAll(searchMap);
    	for(Dict dict : dictList){
    		Map<String,Object> tempMap = MapUtil.newHashMap();
    		tempMap.put("id", dict.getId());
    		tempMap.put("leaf", true);
    		tempMap.put("text", dict.getKey());
    		tempMap.put("en",dict.getType());
    		tempMap.put("state", dict.getState());
    		resultZtreeDate.add(tempMap);
    	}
    	resultMap.put("root", resultZtreeDate);
    	return resultZtreeDate;
    }
    
    @RequestMapping(value="zTree",method= {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    @ApiOperation(value="根据字典类型和字典值获取下级数据，主要是给zTree提供使用")
	@ApiImplicitParams({
        @ApiImplicitParam(name = "type", value = "字典分类类型", required = true, dataType = "String"),
        @ApiImplicitParam(name = "code", value = "字典值", required = true, dataType = "String")
	})
    public Object Ztree(HttpServletRequest request,String type,String code){
    	Map<String,Object> resultMap = MapUtil.newHashMap();
    	List<Map<String,Object>> resultZtreeDate = new ArrayList<Map<String,Object>>();
    	for(String str : type.split(",")) {
    		Map<String,Object> searchMap = MapUtil.newHashMap();
    		searchMap.put("type", str);
        	searchMap.put("state",1);
        	if(!StringUtils.isEmpty(code)){
        		searchMap.put("parent",code);
        	}
        	List<Dict> dictList = services.selectAll(searchMap);
        	for(Dict dict : dictList){//不用递归原因 树最多只让有两层所以没必要递归
        		String dictType = dict.getType();
        		Map<String,Object> tempMap = MapUtil.newHashMap();
        		tempMap.put("id", dict.getId());
        		tempMap.put("text", dict.getKey());
        		tempMap.put("value",dict.getValue());
        		tempMap.put("types", dictType);
        		//第二层
        		Map<String,Object> child = MapUtil.newHashMap();
        		child.put("parent", dict.getId());child.put("state",1);
        		List<Dict> childDict = services.selectAll(child);
        		if(childDict.size() == 0) {
        			tempMap.put("leaf", true);
        		}else {
        			List<Map<String,Object>> childList = new ArrayList<Map<String,Object>>();
        			for(Dict children : childDict) {
        				Map<String,Object> chilMap = MapUtil.newHashMap();
        				chilMap.put("id", children.getId());
        				chilMap.put("text", children.getKey());
        				chilMap.put("value",children.getValue());
        				chilMap.put("types", dictType);
            			//查看第三层
        				Map<String,Object> last = MapUtil.newHashMap();
        				last.put("parent", children.getId());last.put("state",1);
        				List<Dict> childLastDict = services.selectAll(last);
        				if(childLastDict.size() == 0) {
        					chilMap.put("leaf", true);
        				}else {
        					chilMap.put("leaf", false);
        					List<Map<String,Object>> childLastList = new ArrayList<Map<String,Object>>();
        					for(Dict childrenlast : childLastDict) {
        						Map<String,Object> chilLastMap = MapUtil.newHashMap();
        						chilLastMap.put("id", childrenlast.getId());
        						chilLastMap.put("text", childrenlast.getKey());
        						chilLastMap.put("value",childrenlast.getValue());
        						chilLastMap.put("types", dictType);
        						childLastList.add(chilLastMap);
        					}
        					chilMap.put("children", childLastList);
        				}
        				
        				childList.add(chilMap);
        			}
        			tempMap.put("leaf", false);
        			tempMap.put("children", childList);
        		}
        		resultZtreeDate.add(tempMap);
        	}
    	}
    	resultMap.put("text", "根节点");
    	resultMap.put("children", resultZtreeDate);
		return resultMap;
    }
    
    @RequestMapping(value="selectAllByZydm",method=RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value="根据资源代码查询")
	@ApiImplicitParams({
        @ApiImplicitParam(name = "dto", value = "字典实体类型", required = true, dataType = "Dict")
	})
    public Object selectAllByZydm(@Valid Dict dto,HttpServletRequest request, HttpServletResponse response) {
        dto.setKeycodes(StringUtils.StringToList(dto.getKeycode(), ","));
        if(StringUtils.isEmpty(dto.getType())) {
        	return R.fail("请输入字典类型");
        }else {
            return R.success(services.selectAllByQxz(dto));
        }
    }
    
    @ApiLog(value="数据字典数据删除",desc="数据字典数据删除")
    @SuppressWarnings("all")
    @RequestMapping(value="delete",method=RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value="数据字典数据删除")
	@ApiImplicitParams({
        @ApiImplicitParam(name = "ids", value = "要删除的字典技术主键只多个,分割", required = true, dataType = "String")
	})
    public Object delete(String ids,HttpServletRequest request, HttpServletResponse response,
            HttpSession session) throws IOException {
    	boolean isSuccess = false;
    	String[] removes = ids.split(",");
    	for(int i=0;i<removes.length;i++){
    		Dict dict = services.get(removes[i]);
    		isSuccess = services.delete(dict);
    	}
    	return isSuccess?R.success():R.fail();
    }
    
    @ApiLog(value="数据字典数据删除",desc="数据字典数据删除")
    @SuppressWarnings("all")
    @RequestMapping(value="deleteByType",method=RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value="数据字典数据删除")
    @ApiImplicitParams({
    	@ApiImplicitParam(name = "ids", value = "要删除的字典技术主键只多个,分割", required = true, dataType = "String")
    })
    public Object deleteByType(String code) throws IOException {
    	Dict dict = services.get(code); 
    	Map<String,Object> params = new HashMap<String,Object>();
    	params.put("parent", dict.getId());
    	List<Dict> dicts = services.selectAll(params);
    	for(Dict deleteDict : dicts) {
    		services.delete(deleteDict);
    	}
    	services.delete(dict);
    	return R.success();
    }
    
    @ApiLog(value="数据字典数据保存",desc="数据字典数据保存")
    @RequestMapping(value="save",method=RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value="数据字典数据保存")
	@ApiImplicitParams({
        @ApiImplicitParam(name = "dto", value = "字典对象", required = true, dataType = "Dict")
	})
    public Object insert(@Validated Dict dto,HttpServletRequest request, HttpServletResponse response,
            HttpSession session) {
    	dto.setCreater(getName());
    	dto.setCreateDate(new Date(System.currentTimeMillis()));
    	if(services.insert(dto)) {
    		return R.success();
    	}else {
    		return R.fail();
    	}
    }
    
    @ApiLog(value="数据字典数据修改",desc="数据字典数据修改")
    @RequestMapping(value="edit",method=RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value="数据字典数据修改")
	@ApiImplicitParams({
        @ApiImplicitParam(name = "dto", value = "字典对象", required = true, dataType = "Dict")
	})
    public Object update(@Valid Dict dto,HttpServletRequest request, HttpServletResponse response,
            HttpSession session) {
    	dto.setLastModifier(getName());
    	dto.setLastModifyDate(new Date(System.currentTimeMillis()));
    	if(services.update(dto)){
        	return R.success();
    	}else{
    		return R.fail();
    	}
    }
    
    @RequestMapping(value="find",method=RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value="数据字典数据单条记录查询")
	@ApiImplicitParams({
        @ApiImplicitParam(name = "code", value = "字典数据技术主键", required = true, dataType = "Dict")
	})
    public Object get(@NotNull(message="字典编号不能为空") String code, HttpServletRequest request, HttpServletResponse response,
            HttpSession session) {
        return services.get(code);
    }
}
